<template>
  <div class="project-list">
    <div class="page-header">
      <div class="header-left">
        <h1>项目管理</h1>
        <p>集中管理所有众筹项目</p>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="showAdd">
          <el-icon><Plus /></el-icon>
          新增项目
        </el-button>
      </div>
    </div>

    <!-- 筛选和搜索 -->
    <el-card class="filter-card" shadow="never">
      <el-row :gutter="16">
        <el-col :span="6">
          <el-input
            placeholder="项目名称"
            clearable
            v-model="data.searchVo.title"
          >
          </el-input>
        </el-col>
        <el-col :span="6">
          <el-select
            placeholder="项目状态"
            clearable
            v-model="data.searchVo.status"
          >
            <el-option
              v-for="item in data.statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-select
            placeholder="项目分类"
            v-model="data.searchVo.categoryId"
            clearable
          >
            <el-option
              v-for="c1 in data.categoryList"
              :key="c1.categoryId"
              :label="c1.categoryName"
              :value="c1.categoryId"
            />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="load">快捷查询</el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 项目表格 -->
    <el-card class="table-card" shadow="hover">
      <el-table :data="data.projects" v-loading="loading">
        <el-table-column type="selection" width="55" />
        <el-table-column label="项目信息" min-width="250">
          <template #default="{ row }">
            <div class="project-info">
              <el-image
                :src="row.coverImageUrl"
                fit="cover"
                style="width: 80px; height: 60px; border-radius: 4px"
              />
              <div class="project-details">
                <h4>{{ row.title }}</h4>
                <p>{{ row.categoryName }} | 发起人: {{ row.creatorName }}</p>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="目标金额"
          prop="goalAmount"
          width="120"
          align="center"
        >
          <template #default="{ row }"
            >¥{{ formatNumber(row.goalAmount) }}</template
          >
        </el-table-column>
        <el-table-column
          label="已筹金额"
          prop="currentAmount"
          width="120"
          align="center"
        >
          <template #default="{ row }"
            >¥{{ formatNumber(row.currentAmount) }}</template
          >
        </el-table-column>
        <el-table-column label="进度" width="150">
          <template #default="{ row }">
            <el-progress
              :percentage="getPercentage(row)"
              :color="getStatus(row.status).color"
            />
          </template>
        </el-table-column>
        <el-table-column label="状态" width="120" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatus(row.status).type" size="small">{{
              getStatus(row.status).text
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" align="center">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              @click="showUpdate(row.id)"
              link
              >编辑</el-button
            >
            <el-button
              v-if="row.status === 'AUDITING'"
              type="success"
              size="small"
              @click="showAudit(row.id)"
              link
            >
              审核
            </el-button>
            <el-button type="danger" size="small" @click="del(row.id)" link
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="data.currentPage"
          v-model:page-size="data.pageSize"
          :page-sizes="[5, 10, 15]"
          v-model:total="data.total"
          layout="total, sizes, prev, pager, next, jumper"
          @current-change="handleSearch"
          @size-change="handleSearch"
        />
      </div>
    </el-card>

    <!-- 新增/编辑项目对话框 -->
    <el-dialog width="700px" v-model="data.showAddDialog">
      <el-form label-width="100px">
        <el-form-item label="项目名称"
          ><el-input v-model="data.project.title"
        /></el-form-item>
        <el-form-item label="副标题"
          ><el-input v-model="data.project.subtitle"
        /></el-form-item>
        <el-form-item label="发起人">
          <el-select
            placeholder="请选择发起人"
            v-model="data.project.creatorId"
          >
            <el-option
              v-for="c in data.creatorList"
              :key="c.userId"
              :label="c.userNickname"
              :value="c.userId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="项目分类">
          <el-select placeholder="请选择分类" v-model="data.project.categoryId">
            <el-option
              v-for="c1 in data.categoryList"
              :key="c1.categoryId"
              :label="c1.categoryName"
              :value="c1.categoryId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="目标金额"
          ><el-input-number :min="0" v-model="data.project.goalAmount"
        /></el-form-item>
        <el-form-item label="项目封面">
          <img :src="uploadData.imageSrc" class="pic" />
          <el-upload
            :http-request="customUpload"
            list-type="text"
            :before-upload="beforeUpload"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
          >
            <el-button type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="项目简介"
          ><el-input type="textarea" v-model="data.project.detailsContent"
        /></el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="hideAdd">取消</el-button>
        <el-button type="primary" @click="save">确定</el-button>
      </template>
    </el-dialog>
    <!-- 编辑项目对话框 -->
    <el-dialog width="700px" v-model="data.showUpdateDialog">
      <el-form label-width="100px">
        <el-form-item label="项目名称"
          ><el-input v-model="data.project.title" readonly
        /></el-form-item>
        <el-form-item label="副标题"
          ><el-input v-model="data.project.subtitle" readonly
        /></el-form-item>

        <el-form-item label="项目分类">
          <el-select placeholder="请选择分类" v-model="data.project.categoryId">
            <el-option
              v-for="c1 in data.categoryList"
              :key="c1.categoryId"
              :label="c1.categoryName"
              :value="c1.categoryId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="目标金额"
          ><el-input-number :min="0" v-model="data.project.goalAmount"
        /></el-form-item>

        <el-form-item label="项目简介"
          ><el-input type="textarea" v-model="data.project.detailsContent"
        /></el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="hideUpdate">取消</el-button>
        <el-button type="primary" @click="saveUpdate">确定</el-button>
      </template>
    </el-dialog>

    <!-- 审核项目对话框 -->
    <el-dialog title="项目审核" width="500px" v-model="data.showAuditDialog">
      <div>
        <p><strong>项目名称:</strong>{{ data.project.title }}</p>
        <p><strong>发起人:</strong>{{ data.project.creatorName }}</p>
        <p><strong>目标金额:</strong>{{ data.project.goalAmount }}</p>
      </div>
      <el-form label-width="100px" style="margin-top: 20px">
        <el-form-item label="审核意见" prop="action">
          <el-radio-group v-model="data.projectStatus">
            <el-radio label="approve">通过</el-radio>
            <el-radio label="reject">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="备注"
          prop="remarks"
          v-if="data.projectStatus == 'reject'"
        >
          <el-input type="textarea" placeholder="请输入拒绝原因" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="hideAudit">取消</el-button>
        <el-button type="primary" @click="doAudit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus, Search } from "@element-plus/icons-vue";
import http from "@/utils/http";
import axios from "axios";

//显示审核对话框
const showAudit = (id) => {
  data.showAuditDialog = true;
  //加载项目信息
  shwoProject(id);
};
//隐藏审核对话框
const hideAudit = () => {
  data.project = {
    creatorId: 1,
    categoryId: 1,
    title: "",
    subtitle: "",
    coverImageUrl:
      "https://images.unsplash.com/photo-1507925921958-8a62f3d1a50d",
    detailsContent: "",
    goalAmount: 0,
  };
  data.showAuditDialog = false;
};
//处理审核
const doAudit = () => {
  if (data.projectStatus == "approve") {
    data.project.status = "FUNDRAISING"; //众筹中
  } else {
    data.project.status = "REJECT"; //拒绝
  }
  //调用接口更新状态
  http
    .patch("http://localhost:8882/project/update", data.project)
    .then((res) => {
      if (res.code == "1") {
        load(); //重新加载数据
        data.project = {
          creatorId: 1,
          categoryId: 1,
          title: "",
          subtitle: "",
          coverImageUrl:
            "https://images.unsplash.com/photo-1507925921958-8a62f3d1a50d",
          detailsContent: "",
          goalAmount: 0,
        };
        data.projectStatus = "approve";
        data.showAuditDialog = false;
        ElMessage.success("审核成功!");
      } else {
        ElMessage.success("审核失败!");
      }
    });
};
//显示编辑对话框
const showUpdate = (id) => {
  data.showUpdateDialog = true;
  loadcategory();
  //加载项目信息
  shwoProject(id);
};
//加载项目信息
const shwoProject = (id) => {
  http.get("http://localhost:8882/project/get/" + id).then((res) => {
    data.project = res.data;
  });
};
//保存更新
const saveUpdate = () => {
  http
    .patch("http://localhost:8882/project/update", data.project)
    .then((res) => {
      if (res.code == "1") {
        load(); //重新加载数据
        data.project = {
          creatorId: 1,
          categoryId: 1,
          title: "",
          subtitle: "",
          coverImageUrl:
            "https://images.unsplash.com/photo-1507925921958-8a62f3d1a50d",
          detailsContent: "",
          goalAmount: 0,
        };
        data.showUpdateDialog = false;
        ElMessage.success("更新成功!");
      } else {
        ElMessage.success("更新失败!");
      }
    });
};
const hideUpdate = () => {
  data.project = {
    creatorId: 1,
    categoryId: 1,
    title: "",
    subtitle: "",
    coverImageUrl:
      "https://images.unsplash.com/photo-1507925921958-8a62f3d1a50d",
    detailsContent: "",
    goalAmount: 0,
  };
  data.showUpdateDialog = false;
};

const loading = ref(false);
let uploadData = reactive({
  imageSrc: "https://images.unsplash.com/photo-1507925921958-8a62f3d1a50d",
  fileName: "",
});
let customUpload = async (option) => {
  //上传触发
  const formData = new FormData();
  formData.append("file", option.file); //option.file要上传的文件

  try {
    const response = await axios.post(
      "http://localhost:8882/upload",
      formData,
      {
        headers: {
          "Content-Type": "multipart/form-data",
        },
      }
    );
    ElMessage.success("上传成功");
    option.onSuccess(response.data);
  } catch (error) {
    ElMessage.error("上传失败");
    option.onError(error);
  }
};
let beforeUpload = (file) => {
  //上传之前触发
  data.fileName = file.name;
  return true;
};
let handleUploadSuccess = (response) => {
  //上传成功触发
  if (response) {
    uploadData.imageSrc = response; //回显上传的图片

    //得到文件链接存入coverImageUrl
    data.project.coverImageUrl = response;
  }
};
let handleUploadError = (error) => {
  //上传失败触发
  ElMessage.error("上传失败:" + error);
};

const data = reactive({
  projectStatus: "approve",
  showAddDialog: false,
  showUpdateDialog: false,
  showAuditDialog: false,
  projects: [],
  currentPage: 1,
  pageSize: 5,
  total: 10,
  creatorList: [],
  categoryList: [],
  project: {
    creatorId: 1,
    categoryId: 1,
    title: "",
    subtitle: "",
    coverImageUrl:
      "https://images.unsplash.com/photo-1507925921958-8a62f3d1a50d",
    detailsContent: "",
    goalAmount: 0,
  },
  statusOptions: [
    { label: "待审核", value: "AUDITING" },
    { label: "众筹中", value: "FUNDRAISING" },
    { label: "成功", value: "SUCCESSFUL" },
    { label: "失败", value: "FAILED" },
    { label: "已拒绝", value: "REJECT" },
  ],
  searchVo: {
    categoryId: "",
    title: "",
    status: "",
  },
});
//保存项目
const save = () => {
  http.post("http://localhost:8882/project/save", data.project).then((res) => {
    if (res.code == 1) {
      ElMessage.success("添加成功!");
      data.project = {
        creatorId: 1,
        categoryId: 1,
        title: "",
        subtitle: "",
        coverImageUrl:
          "https://images.unsplash.com/photo-1507925921958-8a62f3d1a50d",
        detailsContent: "",
        goalAmount: 0,
      };

      load(); //重新加载
    } else {
      data.project = {
        creatorId: 1,
        categoryId: 1,
        title: "",
        subtitle: "",
        coverImageUrl:
          "https://images.unsplash.com/photo-1507925921958-8a62f3d1a50d",
        detailsContent: "",
        goalAmount: 0,
      };
      ElMessage.error("添加失败!");
    }
  });

  data.showAddDialog = false;
};
//删除
const del = (id) => {
  http.delete("http://localhost:8882/project/delete/" + id).then((res) => {
    if (res.code == 1) {
      ElMessage.success("删除成功!");
      load();
    } else {
      ElMessage.error("删除失败!");
    }
  });
};
//加载发起人列表
const loadcreator = () => {
  //调用接口获取所有的发起人
  http.get("http://localhost:8881/user/list").then((res) => {
    data.creatorList = res.data;
  });
};
//加载项目分类列表
const loadcategory = () => {
  http.get("http://localhost:8883/category/list").then((res) => {
    data.categoryList = res.data;
  });
};
const showAdd = () => {
  loadcreator();
  loadcategory();
  data.showAddDialog = true;
};
const hideAdd = () => {
  data.project = {
    creatorId: 1,
    categoryId: 1,
    title: "",
    subtitle: "",
    coverImageUrl:
      "https://images.unsplash.com/photo-1507925921958-8a62f3d1a50d",
    detailsContent: "",
    goalAmount: 0,
  };
  data.showAddDialog = false;
};
const load = () => {
  http
    .post(
      "http://localhost:8882/project/project/" +
        data.currentPage +
        "/" +
        data.pageSize,
      data.searchVo
    )
    .then((res) => {
      data.projects = res.data.list;
      data.currentPage = res.data.pageNum;
      data.pageSize = res.data.pageSize;
      data.total = res.data.total;
    });
};
//挂载函数
onMounted(() => {
  load();
  loadcategory();
});

const getStatus = (status) => {
  const map = {
    AUDITING: { text: "待审核", type: "warning", color: "#e6a23c" },
    FUNDRAISING: { text: "众筹中", type: "primary", color: "#409eff" },
    SUCCESSFUL: { text: "成功", type: "success", color: "#67c23a" },
    FAILED: { text: "失败", type: "danger", color: "#f56c6c" },
    REJECT: { text: "已拒绝", type: "info", color: "#909399" },
  };
  return map[status] || { text: "未知", type: "info", color: "#909399" };
};

const getPercentage = (project) =>
  Math.min(Math.floor((project.currentAmount / project.goalAmount) * 100), 100);
const formatNumber = (num) => num.toLocaleString();
const handleSearch = () => {
  //重新查询
  load();
};
</script>

<style scoped>
.project-list {
  max-width: 1200px;
  margin: 0 auto;
}
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}
.header-left h1 {
  font-size: 24px;
  font-weight: 700;
  color: #333;
  margin-bottom: 4px;
}
.header-left p {
  color: #666;
  font-size: 14px;
}
.filter-card,
.table-card {
  margin-bottom: 24px;
  border-radius: 12px;
}
.project-info {
  display: flex;
  align-items: center;
  gap: 12px;
}
.project-details h4 {
  font-size: 16px;
  margin: 0 0 4px 0;
}
.project-details p {
  font-size: 12px;
  color: #666;
  margin: 0;
}
.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 24px;
}
:deep(.el-table th) {
  background-color: #f8f9fa;
  color: #333;
  font-weight: 600;
}
.pic {
  width: 150px;
  height: 150px;
  border: 1px solid black;
  border-radius: 5px;
}
</style> 